// pages/startBluetooth/startBlue.js
let app = getApp();
let bluetoothtool = require("../../utils/bluetoothtool.js");
var httptool = require("../../utils/zry.httptool.js");
var tabjs = require("../../utils/tab.js");
Page({
  data:{
    blueTooths: [],
    authTokenRegister:'',//是否注册
    compuInfo:'',//提示注册的信息
    activeIndex:'1',
    isshow:false,
    msgprop:'',//消息提示 
    isconnect:false,
    devices:[],
    blebreak:0,
    blueToothsCount:0
  }, 
  myCenter:function(e){
    wx.redirectTo({
      url: '/pages/myCenter/myCenter',
    })
  },
  leiCircle:function(e){
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  checkRule:function(){//查看规则
    wx.navigateTo({
      url: '/pages/daleiRule/leirule',
    })
  },
  onLoad:function(options){
    let self = this;
    if (options.blebreak == 1)
      self.setData({ blebreak: options.blebreak });
    httptool.login(function () {
      // 页面初始化 options为页面跳转所带来的参数
      httptool.ajaxPost("api/Device/GetMyConnectDevices", {}, function (res) {//设备列表
        if (res.suc) {
          let data = app.notNull(res.data, []);
          self.setData({ devices: data });
        }
      });
    });
  },
  scanQRCode: function () {
    let self = this;
    httptool.login(function () {
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          console.log("results=" + res.result);
          bluetoothtool.checkBLEIsOpen(self, function (result) {
            if (result == 1) {
              bluetoothtool.searchDevices(function (devices) {
                console.log(devices);
                self.updateBlueTooths(devices, res.result);
              });
            } else if (result == 0) {
              bluetoothtool.openBlueTooth(self, function (devices) {
                self.updateBlueTooths(devices, res.result);
              });
            }
          });
        }
      });
    });
  },
  //1.开启蓝牙适配，并启用适配监听
  openBlueTooth:function(){    
    let self=this;
    httptool.login(function () {
      app.showLoading({title:"正在搜索"});
      wx.closeBluetoothAdapter();
      setTimeout(function(){
        bluetoothtool.checkBLEIsOpen(self, function (result) {
          if (result == 1) {
            bluetoothtool.searchDevices(function (devices) {
              self.updateBlueTooths(devices, '');
            });
          } else if (result == 0) {
            bluetoothtool.openBlueTooth(self, function (devices) {
              self.updateBlueTooths(devices, '');
            });
          }
          wx.hideLoading();
        }, function () { wx.hideLoading(); });
      },500);      
    });
  },
  connectBlueToothhandle:function(e){
    let self=this;
    let deviceId = e.currentTarget.dataset.idx;
    let deviceName = e.currentTarget.dataset.name;
    let localName = e.currentTarget.dataset.localname;
    console.log("deviceName=" + deviceName);  
    console.log("localName=" + localName);
    self.connectBlueTooth(deviceId, deviceName, localName);
    
  },
  connectBlueTooth: function (deviceId, deviceName, localName){
    let self = this;
    if (!self.data.isconnect){
      self.setData({ isconnect: true });
      app.showLoading({ title: "正在连接中" });
      bluetoothtool.startConnectDevices(self, deviceId, deviceName, function () {
        httptool.ajaxPost("api/Device/EditDevice", { SNCode: deviceName, OtherName: localName });
        app.showLoading({ title: "正在初始化配置" });
        setTimeout(function () {
          wx.redirectTo({
            url: '/pages/contest/contest?deviceId=' + deviceId + '&deviceName=' + deviceName
          });
        }, 5000);
      });
    }    
  },
  updateBlueTooths(devices, name) {
    let self = this;
    let blueTooths = [];
    for (let i in devices){
      let deviceName = devices[i]['name'];
      if (deviceName == "" || deviceName.toLowerCase().indexOf("redbuff") != 0 ){
        continue;
      }      
      if(name){
        if (devices[i]['name'] == name) {
          self.connectBlueTooth(devices[i]['deviceId'], name, self.getDeviceOtherName(devices[i]['name']));
          break;
        }
      }
      if (!self.checkBlueToothIsExist(devices[i]['deviceId'], blueTooths)){
        let blueTooth = {};
        blueTooth.deviceId = devices[i]['deviceId'];
        blueTooth.name = devices[i]['name'];
        console.log("blueTooth.name=" + blueTooth.name);
        blueTooth.localName = self.getDeviceOtherName(blueTooth.name);
        blueTooths.push(blueTooth);
      }
    }
    let isshow = blueTooths.length==0;
    self.setData({ blueTooths: blueTooths, isshow: isshow && self.data.blueToothsCount > 0, 
    blueToothsCount: self.data.blueToothsCount + 1 });
  },
  checkBlueToothIsExist(deviceId, blueTooths)
  {
    for (let j in blueTooths) {
      if (blueTooths[j]['deviceId'] == deviceId){
        return true;
      }
    }
    return false;
  },
  getDeviceOtherName:function(snCode){
    let devices = this.data.devices;
    if (devices.length>0){
      for (let i in devices) {
        if (devices[i].SNCode == snCode){
          return devices[i].OtherName;
        }
      }
    }
    return snCode;
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){    
    if (this.data.blebreak==1){
      app.showNotify(this, "请注意，手机蓝牙与设备断开连接！");
    }
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  }
})